package com.huimin.merchant.controller;

import com.huimin.merchant.common.util.SecurityUtil;
import com.huimin.merchant.convert.MerchantRegisterConvert;
import com.huimin.merchant.dto.MerchantDTO;
import com.huimin.merchant.service.FileService;
import com.huimin.merchant.service.MerchantServiceApi;
import com.huimin.merchant.service.SmsService;
import com.huimin.merchant.vo.MerchantRegisterVO;
import io.swagger.annotations.*;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author ymx
 */
@Api(value = "商户平台‐商户相关", tags = "商户应用Api接口11", description = "商户应用Api接口22")
@RestController
@RefreshScope
public class MerchantController {

	@Reference
	private MerchantServiceApi merchantService;

	@Autowired
	private SmsService smsService;

	@Autowired
	private FileService fileService;


	@ApiOperation(value = "根据id查询商户")
	@GetMapping("/merchants/{id}")
	public MerchantDTO findMerchantById(@PathVariable("id") Long id) {

		return merchantService.findMerchantById(id);

	}


	@ApiOperation(value = "获取验证码")
	@ApiImplicitParam(value = "手机号", name = "mobile", required = true, dataType = "String", paramType = "query")
	@GetMapping("/sms")
	public String getSmsCode(@RequestParam("mobile") String mobile) {

		return smsService.getSmsCode(mobile);
	}


	@ApiOperation(value = "注册商户")
	@ApiImplicitParam(name = "MerchantRegisterVO", value = "注册信息",
			required = true, dataType = "MerchantRegisterVO", paramType = "body")
	@PostMapping("/merchants/register")
	public MerchantRegisterVO registerMerchant(MerchantRegisterVO merchantRegisterVO) {

		// TODO: 2020/12/2  校验修改

		//	1. 校验验证码
		smsService.checkSmsCode(merchantRegisterVO.getVerifiykey(), merchantRegisterVO.getVerifiyCode());

		//	2. 添加商户
		// MerchantDTO merchantDTO = new MerchantDTO();
		// BeanUtils.copyProperties(merchantRegisterVO, merchantDTO);
		MerchantDTO merchantDTO = MerchantRegisterConvert.INSTANCE.vo2dto(merchantRegisterVO);

		merchantService.registerMerchant(merchantDTO);

		return merchantRegisterVO;

	}


	@ApiOperation("证件上传")
	@PostMapping("/upload")
	@ApiParam(value = "上传的文件", required = true)
	public String upload(@RequestParam("file") MultipartFile file) throws Exception {


		return fileService.upload(file);
	}


	@ApiOperation("商户资质申请")
	@ApiImplicitParams({@ApiImplicitParam(name = "merchantDto", value = "商户认证资料", required = true, dataType =
			"MerchantDTO", paramType = "body")})
	@PostMapping("/my/save")
	public void saveMerchant(@RequestBody MerchantDTO merchantDto) {
//        Long merchantId= 1L; //Bearer eyJtZXJjaGFudElkIjoxLCJ1c2VyX25hbWUiOiIxMDAiLCJtb2JpbGUiOiIxMDAifQ==
		Long merchantId = SecurityUtil.getMerchantId();
		merchantService.applyMerchant(merchantId, merchantDto);
	}


}
